#include"tcpsocket.hpp"
#include"cala.hpp"
#include<signal.h>
using namespace std;

#define CHECK_RET(r) if((r) == false){return -1;}
int main(int argc,char *argv[]){
    if(argc!=3){
        cout<<"usage:./tcp_cli 127.168.2.2 9000\n";
        return -1;
    }
    signal(SIGPIPE,SIG_IGN);
    string ip=argv[1];
    uint16_t port=stoi(argv[2]);
    TcpSocket cli_sock;
    //创建套接字
    CHECK_RET(cli_sock.Socket());
    //绑定地址信息(不推荐)->向服务端发起连接
    CHECK_RET(cli_sock.Connect(ip,port));
    while(1){
    //收发数据
        int num1,num2;
        char op;
        cout<<"input arithmetic expression:";
        fflush(stdout);
        //string body;
        cin>>num1>>op>>num2;
        cala_t tmp(num1,num2,op);
        //int fd=cli_sock.Fd();
        //send(fd,&tmp,sizeof(cala_t),0);
        //int result;
        //recv(fd,&result,sizeof(int),0);
        //cout<<"result:"<<result<<endl;

        string body;
        body.assign((char*)&tmp,sizeof(cala_t));
        CHECK_RET(cli_sock.Send(body));
        CHECK_RET(cli_sock.Recv(&body));
        cout<<"result:"<<*(int*)&body[0]<<endl;
    }
    //关闭套接字
    cli_sock.Close();
    return 0;
}
//连接断开后，对于程序的影响：
// recv:recv将不再阻塞,而是返回0表示连接断开
// send:send发送数据的时候，会触发异常SIGPIPE(所有读端关闭)，导致程序退出